package org.xiyinjihe.platform.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.xiyinjihe.platform.annotation.Check;
import org.xiyinjihe.platform.dto.resp.ExceptionDTO;
import org.xiyinjihe.platform.enums.ResponseStatus;
import org.xiyinjihe.platform.error.CommonError;
import org.xiyinjihe.platform.exception.CommonException;
import org.xiyinjihe.platform.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class PermissionInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(PermissionInterceptor.class);

    private String sessionKey = "token";

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            logger.debug("preHandle -----" + ((HandlerMethod) handler).getMethod().getName());
            // 获取方法上的注解
            Check check = ((HandlerMethod) handler).getMethod().getAnnotation(Check.class);
            // 如果方法上的注解为空 则获取类的注解
            if (check == null) {
                check = ((HandlerMethod) handler).getMethod().getDeclaringClass().getAnnotation(Check.class);
            }
            if (check == null) {
                return true;
            }

            //获取请求url
            String url = httpServletRequest.getRequestURI();
            String token = httpServletRequest.getHeader("Authorization");
            if(!userService.isTokenValidate(token)){
//                httpServletResponse.setContentType("application/json; charset=UTF-8");
//                httpServletResponse.setStatus(403);
//                ExceptionDTO exceptionDTO = new ExceptionDTO();
//                exceptionDTO.setStatus(ResponseStatus.FAIL);
//                exceptionDTO.setErrorMsg("权限不足,请联系管理员!");
//                Gson gson = new Gson();
//                String result = gson.toJson(exceptionDTO);
//                httpServletResponse.getWriter().print(result);
                throw new CommonException(CommonError.AUTH_ERROR,"权限不足,请联系管理员!");
            }else{
                try {
                    DecodedJWT decode = JWT.decode(token);
                    long userId = decode.getHeaderClaim("userId").asLong();
                    httpServletRequest.getSession().setAttribute("userId",userId);
                } catch (JWTDecodeException e) {
                    throw new CommonException(CommonError.AUTH_ERROR,e,"无法获取用户信息");
                }
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
